<?php

namespace App\Http\Api\Controllers\Order;

use App\Exceptions\InvalidRequestException;

use App\Http\Api\Services\FxgService;
use App\Http\Controllers\Controller;
use App\Http\Models\Product;
use App\Http\Models\ProductSku;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use UpdateHelper\NotUpdateInterfaceInstanceException;


class FxgGoodsUpApiController extends Controller
{
    protected $fxgService;

    public function __construct(FxgService $fxgService)
    {
        $this->fxgService = $fxgService;
    }

    public function createProd(Request $request){
        $prod_no    = $request->input('prod_no') ?? 'Hj123456';
        $type       = $request->input('type') ?? '1';//1 添加 2 编辑
        $brand_id   = $request->input('brand') ?? '14322';//品牌
        $result = [];
        if(!empty($prod_no)){
            /*
             * 1、规格上传，得spec_id
             * 2、产品上传
             * 3、上传sku
             */
            $prodShops  =    DB::table('admin_products_shops')->where('prod_no',$prod_no)->get()->toArray();

            foreach ($prodShops as $k=>$v){
                $product = Product::where('prod_no',$v->prod_no)->with('skus')->first();//产品信息

                /*
                 * 1、上传规格
                 */
                $data   =  $this->makeData($product,$v->shop_id);//整理规格数据
                //规格名称 : 厂家#厂家货号+名称#成本#内部货号
                $data['spec_name']  =   $product->manu_name.'#'.$product->manu_no.'+'.$product->prod_name.'#'.$product->cost_price.'#'.$product->prod_no;
                $resultSpec    =   $this->fxgService->addGoodsSpec($data);//上传规格
                $data['spec_id']        =   $resultSpec['data']['id'] ?? ''; //规格id
                $data['skus']           =   $this->makeSkus($product,$resultSpec,$data);//整理sku数据
                /*
                 * 2、上传产品
                 */
                $data['brand'] = $brand_id;
                if($type == 1){ //  添加
                    $data['out_product_id']     =   strtotime(date("Y-m-d H:i:s"));
                    $data['type'] = 1;
                    $data['param_json']     =   $this->makeGoods($product,$data);//商品数据整理
                    $resultGoods  =   $this->fxgService->addGoods($data);//添加商品
                }else{  //编辑
                    $data['out_product_id']     =   $product->goods_id;//放心购平台产品id
                    $data['type'] = 2;
                    $data['param_json']     =   $this->makeGoods($product,$data);//商品数据整理

                    $resultGoods  =   $this->fxgService->editGoods($data);//添加商品
                }
                /*
                 * 2、上传SKU
                 */
                $resultSkus     =   $this->fxgService->addGoodsSkus($data);//上传sku

                array_push($result,$resultSpec);
                array_push($result,$data);
                array_push($result,$resultGoods);
                array_push($result,$resultSkus);
            }

        }

        return res('上传成功',$result);
    }


    /*整理上传规格数据*/
    public function makeData($product,$shop_id){
        $result = [];
        $shop = DB::table('admin_shop_config')->where('shop_id',$shop_id)->first();
        $result['app_key']      =   $shop->appKey;
        $result['app_secret']   =   $shop->appSecret;
        $result['skus']         =   $product->skus;

        return $result;
    }


    /*整理上传sku数据*/
    public function makeSkus($product,$resultSpec,$data){
        $arr_spec           =   [];
        $spec               =   $resultSpec['data']['Specs'] ?? [];
        $spec1              =   [];
        $spec2              =   [];
        foreach ($spec as $k=>$v){    //三维转二维
            foreach ($v['values'] as $kk=>$vv ){
                array_push($arr_spec,$vv);
            }
            if($k == 0){
                $spec1  =   $v['values'];
            }
            if($k == 1){
                $spec2  =   $v['values'];
            }

        }
        $sku            =   $data['skus'];
        $result_arr     =   [];
        foreach ($spec1 as $k=>$v){
            foreach ($spec2 as $kk=>$vv){
                $color_data     =   collect($sku)->where('sku_color',$v['name'])->where('sku_size',$vv['name'])->first();
                $str1           =   substr($v['id'],-2);
                $str2           =   substr($vv['id'],-2);
                $index          =   $str1.$str2;//生成out_sku_id

                $cost_price =   '99900';
                if($product['cost_price'] >= 600){
                    $cost_price =   '999900';
                }
                if(!empty($color_data)){

                    $result_arr[$index]['spec_detail_ids'] =   $v['id'].'|'.$vv['id'];
                    $result_arr[$index]['name']    =   $color_data['sku_color'].'-'.$color_data['sku_size'] ?? '';
                    $result_arr[$index]['price']   =   $cost_price;
                    $result_arr[$index]['stock']   =   5;
                }else{

                    $result_arr[$index]['spec_detail_ids'] =   $v['id'].'|'.$vv['id'];
                    $result_arr[$index]['name']    =   $v['name'].'-'.$vv['name'] ?? '';
                    $result_arr[$index]['price']   =   $cost_price;
                    $result_arr[$index]['stock']   =   5;
                }
                //厂家#厂家货号+名称#成本#内部货号#售价
                $result_arr[$index]['code']   =   $product->manu_name.'#'.$product->manu_no.'+'.$product->prod_name.'#'.$product->cost_price.'#'.$product->prod_no.'#'.$product->prod_price;

            }
        }

        return $result_arr;
    }

    /*整理产品上传数据*/
    public function makeGoods($product,$data){

        $param_json =   '';
        if(!empty($data['spec_id'])){
            $brand_id       =   $data['brand'] ?? '14322';//美丽演绎
            //$discount_price =   $product['prod_price']*100;    //活动价
            $out_product_id =   $data['out_product_id'];    //产品id
            $name           =   $product['prod_name'].' '.$product['prod_no'];  //  产品名称
            $cost_price =   '99900';//金额：999(成本>600的，9999)
            if($product['cost_price'] >= 600){
                $cost_price =   '999900';
            }
            $discount_price =   $market_price   =   $cost_price;
            $product_format =   '14322';//美丽演绎
            $mobile         =   '15359780390';
            $third_cid      =   $product['third_cid'];
            $spec_id        =   $data['spec_id'];
            /*产品图 xx|xx 详情图  xx|xx*/
            $prodImg    =   json_decode($product['prodImg'],true);
            $descImg    =   json_decode($product['descImg'],true);
            $pic    =   implode("|",$prodImg);
            $desc   =   implode("|",$descImg);
            /*sku图片spec*/
            $arrIds = [];
            foreach ($data['skus'] as $k=>$v){
                $ids = explode('|',$v['spec_detail_ids']);
                array_push($arrIds,$ids[0]);
            }
            $arrIds     =   array_unique($arrIds);
            if($data['type'] == 2){
                $spec_pic   =   implode("|http://dd.youdnr.com/upload/products/Image//1574243368_93Vz1NLIu7.jpeg^",$arrIds);
                $spec_pic .= '|http://dd.youdnr.com/upload/products/Image//1574243368_93Vz1NLIu7.jpeg';
            }else{
                $spec_pic   =   implode("|^",$arrIds);
            }

            if($data['type'] == 2){
                $param_json =   '{"description":"'.$desc.'","first_cid":"5","pic":"'.$pic.'","product_id":"'.$out_product_id.'","second_cid":"48","spec_id":"'.$spec_id.'","spec_pic":"'.$spec_pic.'","third_cid":"'.$third_cid.'","weight":"1000"}';
            }else{
                $param_json =   '{"brand_id":"'.$brand_id.'","cos_ratio":"1","description":"'.$desc.'","discount_price":"'.$discount_price.'","first_cid":"5","market_price":"'.$market_price.'","mobile":"'.$mobile.'","name":"'.$name.'","out_product_id":"'.$out_product_id.'","pay_type":"1","pic":"'.$pic.'","product_format":"'.$product_format.'","second_cid":"48","spec_id":"'.$spec_id.'","spec_pic":"'.$spec_pic.'","third_cid":"'.$third_cid.'","weight":"1000"}';
            }


        }


        return $param_json;

    }

    //获取店铺授权品牌
    public function getBrand(Request $request){
        $shop_id        =   $request->input('shop_id') ?? '';
        $brand_list = [];
        if(!empty($shop_id)){
            $shop = DB::table('admin_shop_config')->where('shop_id',$shop_id)->first();
            $APP_KEY        =   $shop->appKey;
            $APP_SECRET     =   $shop->appSecret;


            $attributes['APP_KEY']      =   $APP_KEY;
            $attributes['APP_SECRET']   =   $APP_SECRET;
            $attributes['timestamp']    =   date('Y-m-d H:i:s', time());
            $attributes['c']            =   'shop';
            $attributes['a']            =   'brandList';
            $attributes['param_json']   =   '{}';

            $brand_list =   $this->fxgService->sendFxgRequest($attributes);
        }



        return $brand_list;
    }
}